/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mobiwebinc.compconn.events;

import com.mobiwebinc.compconn.communication.SystemController;
import com.mobiwebinc.compconn.events.command.Command;
import com.mobiwebinc.compconn.events.command.Decoder;
import java.awt.event.KeyEvent;

/**
 *
 * @author suraj
 */
public class Keyboard implements EventHandler {


    public void handleRequest(String cmd) {
        if (cmd.startsWith(Command.KEY_UP)) {
            keyUp(cmd);
        } else if (cmd.startsWith(Command.KEY_DOWN)) {
            keyDown(cmd);
        }
    }

    private int keyCode(String key) {
        int code = 0;
        try {
            code = KeyEvent.class.getField(key.toUpperCase()).getInt(KeyEvent.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return code;
    }

    private void keyDown(String cmd) {
        String[] params = Decoder.stringParameters(cmd);
        int code = keyCode(params[0]);
        if(code != 0)
            SystemController.getInstance().keyPress(code);
    }

    private void keyUp(String cmd) {
        String[] params = Decoder.stringParameters(cmd);
        int code = keyCode(params[0]);
        if(code != 0)
            SystemController.getInstance().keyRelease(code);
    }

    public boolean isSupported(String cmd) {
        return cmd.startsWith(Command.KEY_PREFIX);
    }
}
